package utils

import (
	"context"
	"fmt"
	"github.com/go-redis/redis/v8"
	"github.com/spf13/viper"
	"go-vue-blog-sever/config"
	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"log"
	"os"
	"time"
)

var (
	MysqlDB      *gorm.DB
	Logger       *zap.Logger
	SugarLogger  *zap.SugaredLogger
	RedisDB      *redis.Client
	RedisContext = context.Background()
)

func init() {
	configInit()
	initLogger()
	mysqlInit()
	initRedis()
}

func configInit() {
	dir, err := os.Getwd()
	if err != nil {
		panic(fmt.Errorf("获取工作路径失败 err=%v", err))
	}
	viper.SetConfigType("yml")
	viper.SetConfigName("config")
	viper.AddConfigPath(dir)
	err = viper.ReadInConfig()
	if err != nil {
		panic(fmt.Errorf("读取配置文件失败 err=%v", err))
	}
}

func initLogger() {
	encoder := config.GetEncoder()
	writerSyncer := config.GetLogWriter()
	core := zapcore.NewCore(encoder, writerSyncer, zapcore.DebugLevel)
	Logger = zap.New(core)
	SugarLogger = Logger.Sugar()
}

func mysqlInit() {
	mysqlConfig := config.NewMysqlConfig()
	if err := mysqlConfig.MysqlTestLink(); err != nil {
		panic(fmt.Errorf("测试数据库连接失败 err=%v", err))
	}
	logs := logger.New(log.New(os.Stdout, "\r\n", log.LstdFlags),
		logger.Config{
			SlowThreshold:             time.Second, //慢sql阀值
			LogLevel:                  logger.Info, //级别
			IgnoreRecordNotFoundError: true,
			Colorful:                  true, //彩色
		})
	err := mysqlConfig.LinkMysql(&MysqlDB, &gorm.Config{Logger: logs})
	if err != nil {
		panic(fmt.Errorf("数据库连接失败 err=%v", err))
	}
}

func initRedis() {
	r := config.NewRedisConfig()
	RedisDB = redis.NewClient(&redis.Options{
		Password: r.Password,
		Addr:     r.Host,
		DB:       r.DB,
	})
	_, err := RedisDB.Ping(RedisContext).Result()
	if err != nil {
		LoggerError("系统错误", fmt.Sprintf("redis 连接失败 err=%v", err), nil)
	}
}
